package com.shankungfu.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.shankungfu.GlobleConstant;
import com.shankungfu.MainApplication;
import com.shankungfu.R;
import com.shankungfu.adapter.BrowseAdapter;
import com.shankungfu.bean.BrowseFindBean;
import com.shankungfu.bean.BrowseFindListBean;
import com.shankungfu.bean.FindDataBean;
import com.shankungfu.bean.RisgterListDataBean;
import com.shankungfu.main.PickItemDetailActivity;
import com.shankungfu.util.TestUtils;
import com.shankungfu.util.ToastUtil;
import com.shankungfu.util.WebService;
import com.shankungfu.view.GeneralDialog.DialogCallBack;

public class BrowseFindFragment extends Fragment implements
		OnItemClickListener, OnClickListener, OnScrollListener {
	private static final int data_success = 1;
	private static final int data_error = 2;
	protected static final int data_empty = 3;
	protected static final int TIME = 10;
	protected static final int PUBLIC = 11;
	protected static final int PEOPLE = 12;
	private static final int AREA = 13;

	private ListView browseListView;
	private BrowseAdapter adapter;
	private List<FindDataBean> list;
	private RelativeLayout progressBar;
	private ImageView head_refresh;
	private Button all_time;
	private Button public_area;
	private Button fit_people;
	private Button all_address;
	
	private String city;
	private String allTime = "不限";
	private String publicArea = "不限";
	private String fitPeople = "不限";
	private String allAddress = "";
	
	private BrowseFindListBean listBean;
	private BrowseFindBean browseFindBean;
	private int pagesize = 1; //当前分页数
	private int visibleLastIndex = 0; //最后的可视项索引
	private int visibleItemCount; // 当前窗口可见项总数
	private View loadMoreView;
	private Button loadMoreButton;
	private ProgressBar loadMoreProgressBar;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			switch (msg.what) {
			case data_success:

				BrowseFindBean browseFindBean = (BrowseFindBean) msg.obj;
				list = browseFindBean.getFindData();
				if(list.size() != 0 && pagesize == 1){
					adapter.setData(list);
				} else if(list.size() != 0 && pagesize > 1){
					adapter.addData(list);

			        browseListView.setSelection(visibleLastIndex - visibleItemCount + 1); //设置选中项
		            loadMoreButton.setText("加载更多");    //恢复按钮文字 
				} else {
					loadMoreProgressBar.setVisibility(View.GONE);
					loadMoreButton.setText("数据加载完毕");
				}
				
				break;
			case data_error:
				list.clear();
				adapter.setData(list);
				loadMoreProgressBar.setVisibility(View.GONE);
				loadMoreButton.setText("数据加载失败，请刷新重试");
				break;
			case data_empty:
				list.clear();
				adapter.setData(list);
				loadMoreProgressBar.setVisibility(View.GONE);
				loadMoreButton.setText("当前城市没有更多项目了");
				break;
			default:
				break;
			}
			adapter.notifyDataSetChanged();
		}

	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = initView(inflater);
		updateForData();

		loadMoreView = inflater.inflate(R.layout.loadmore_layout, null);  
	    loadMoreButton = (Button) loadMoreView.findViewById(R.id.loadmore_btn);
	    loadMoreProgressBar = (ProgressBar) loadMoreView.findViewById(R.id.loadmore_progressbar);
	    
	    browseListView.addFooterView(loadMoreView);   //设置列表底部视图
	    list = new ArrayList<FindDataBean>();
	    
		adapter = new BrowseAdapter(getActivity(), MainApplication.options);
		browseListView.setAdapter(adapter);
		browseListView.setOnScrollListener(this);     //添加滑动监听
		city = MainApplication.getCity();
		getListData(pagesize);
		getData("不限", "不限", "不限", "", pagesize);
		return v;
	}

	private View initView(LayoutInflater inflater) {
		View v = inflater.inflate(R.layout.browse_find_layout, null);

		progressBar = (RelativeLayout) v.findViewById(R.id.progressBar);
		browseListView = (ListView) v.findViewById(R.id.browse_listview);
		head_refresh = (ImageView) getActivity()
				.findViewById(R.id.head_refresh);

		all_time = (Button) v.findViewById(R.id.all_time);
		public_area = (Button) v.findViewById(R.id.public_area);
		fit_people = (Button) v.findViewById(R.id.fit_people);
		all_address = (Button) v.findViewById(R.id.all_address);

		all_time.setOnClickListener(this);
		public_area.setOnClickListener(this);
		fit_people.setOnClickListener(this);
		all_address.setOnClickListener(this);
		head_refresh.setOnClickListener(this);
		browseListView.setOnItemClickListener(this);
		return v;
	}

	private void getListData(int pagesize) {
		WebService httpclient = new WebService();
		RequestParams params = new RequestParams();
		params.add("serviceId", "bslist");
		if (city.contains("省")) {
			city = city.substring(0, city.indexOf("省"));
		} else if (city.contains("市")) {
			city = city.substring(0, city.indexOf("市"));
		}
		params.add("province", city);
		AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, String content) {
				getSuccessData();
				TestUtils.logI("PickItemFragment  statusCode:" + statusCode
						+ ", content:" + content);
				if (!TextUtils.isEmpty(content)
						&& content.contains("\"result\":0")) {
					listBean = JSON.parseObject(content,
							BrowseFindListBean.class);
				}
			}

			@Override
			public void onFailure(Throwable error, String content) {
				TestUtils.logI("error:" + error + ", content:" + content);
			}
		};
		httpclient.request(GlobleConstant.GET_LIST, params, responseHandler);
	}

	private void getData(String time, String publics, String people, String area, int pagesize) {
		WebService httpclient = new WebService();
		RequestParams params = new RequestParams();
		params.add("serviceId", "find");
		params.add("app_info", "shankungfu");
		params.add("time", time);
		params.add("area", publics);
		params.add("group", people);
		params.add("city", area);
		params.add("province", city);
		params.add("page", String.valueOf(pagesize));

		AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, String content) {
				getSuccessData();
				TestUtils.logI("PickItemFragment  statusCode:" + statusCode
						+ ", content:" + content);
				Message msg = Message.obtain();
				if (!TextUtils.isEmpty(content)
						&& content.contains("\"result\":0")) {

					browseFindBean = JSON.parseObject(content,
							BrowseFindBean.class);
					msg.what = data_success;
					msg.obj = browseFindBean;

				} else {
					msg.what = data_empty;
				}
				handler.sendMessage(msg);
			}

			@Override
			public void onFailure(Throwable error, String content) {
				TestUtils.logI("error:" + error + ", content:" + content);
				Message msg = Message.obtain();
				msg.what = data_error;
				handler.sendMessage(msg);
			}
		};
		httpclient.request(GlobleConstant.ACTIVITY_LIST, params,
				responseHandler);
	}

	private void updateForData() {
		progressBar.setVisibility(View.VISIBLE);
	}

	private void getSuccessData() {
		progressBar.setVisibility(View.GONE);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		FindDataBean findDataBean = adapter.getItem(position);

		Intent intent = new Intent(getActivity(), PickItemDetailActivity.class);
		intent.putExtra(PickItemDetailActivity.PROJECT_ID,
				findDataBean.getFind_Id());
		startActivity(intent);
	}

	@Override
	public void onClick(View v) {

		if (listBean != null) {

			switch (v.getId()) {

			case R.id.head_refresh:
				getData("不限", "不限", "不限", "", pagesize);
				updateForData();
				break;
			case R.id.all_time:
				showListDialog(TIME, listBean.getRisgterListData().getTimes());
				break;
			case R.id.public_area:
				showListDialog(PUBLIC, listBean.getRisgterListData()
						.getCategory());
				break;
			case R.id.fit_people:
				showListDialog(PEOPLE, listBean.getRisgterListData().getFits());
				break;
			case R.id.all_address:
				String[] areas = listBean.getRisgterListData().getAreas();
				if (areas.length > 0) {
					showListDialog(AREA, areas);
				} else {
					ToastUtil.showMessageText(getActivity(), "当前全国状态下无城市列表");
				}
				break;
			}
		}
	}

	private void showListDialog(final int categroy, final String[] listData) {
		AlertDialog.Builder listDia = new AlertDialog.Builder(getActivity());
		listDia.setTitle(null);
		listDia.setItems(listData, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				RisgterListDataBean dataBean = listBean.getRisgterListData();
				updateForData();

				// 四个分类，点击某个后就开始刷新数据。
				switch (categroy) {
				case TIME:

					
					String[] times = dataBean.getTimes();
					String time = times[which];

					if (time.equals("选择日期")) {
						// 调用系统的功能，选择时间后，处理数据
						// 初始化Calendar日历对象
						Calendar mycalendar = Calendar
								.getInstance(Locale.CHINA);
						Date mydate = new Date(); // 获取当前日期Date对象
						mycalendar.setTime(mydate);// //为Calendar对象设置时间为当前日期

						DatePickerDialog dpd = new DatePickerDialog(
								getActivity(), new OnDateSetListener() {

									@Override
									public void onDateSet(DatePicker view,
											int year, int monthOfYear,
											int dayOfMonth) {
										String temp = year + "-"
												+ (monthOfYear + 1) + "-"
												+ dayOfMonth;

										setTimeForData(temp);
										allTime = temp;
									}
								}, mycalendar.get(Calendar.YEAR), mycalendar
										.get(Calendar.MONTH), mycalendar
										.get(Calendar.DAY_OF_MONTH));
						dpd.show();
						return;
					}
					
					allTime = time;
					publicArea = "";
					fitPeople = "";
					allAddress = "";
					setTimeForData(time);
					break;
				case PUBLIC:
					String[] publics = dataBean.getCategory();
					String publicStr = publics[which];
					allTime = "";
					publicArea = publicStr;
					fitPeople = "";
					allAddress = "";
					setPublicForData(publicStr);
					break;
				case PEOPLE:
					String[] fits = dataBean.getFits();
					String fitStr = fits[which];
					
					allTime = "";
					publicArea = "";
					fitPeople = fitStr;
					allAddress = "";
					setPeopleForData(fitStr);
					break;
				case AREA:
					String[] areas = dataBean.getAreas();
					String area = areas[which];
					
					allTime = "";
					publicArea = "";
					fitPeople = "";
					allAddress = area;
					setAreaForData(area);
					break;
				}
			}

			private void setAreaForData(String area) {
				getData("", "", "", area, pagesize);
			}

			private void setPeopleForData(String fitStr) {
				getData("", "", fitStr, "", pagesize);

			}

			private void setPublicForData(String publicStr) {
				getData("", publicStr, "", "", pagesize);
			}

			private void setTimeForData(String time) {
				getData(time, "", "", "", pagesize);
			}
		});
		listDia.create().show();
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		this.visibleItemCount = visibleItemCount;  
	    visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		int itemsLastIndex = adapter.getCount() - 1;    //数据集最后一项的索引   
	    int lastIndex = itemsLastIndex + 1;             //加上底部的loadMoreView项   
	    
	    int pageSize = Integer.valueOf(browseFindBean.getPagesize());
	    int count = Integer.valueOf(browseFindBean.getCount());
	    
	    if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex &&
	    		pageSize < count) {  
	        //如果是自动加载,可以在这里放置异步加载数据的代码   
	        Log.i("LOADMORE", "loading...");
	        ++pagesize;
	        
	        getData(allTime, publicArea, fitPeople, allAddress, pagesize);
	    } else {
	    	loadMoreProgressBar.setVisibility(View.GONE);
			loadMoreButton.setText("当前城市没有更多项目了");
		}
	}
}
